package com.studyroom.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studyroom.common.ApiResponse;
import com.studyroom.common.Result;
import com.studyroom.entity.Feedback;
import com.studyroom.service.FeedbackService;
import com.studyroom.service.FileService;
import com.studyroom.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/feedback")
public class FeedbackController {

    @Autowired
    private FeedbackService feedbackService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private FileService fileService;  // 注入文件服务
    @Value("${file.upload.path:../}")
    private String uploadPath;
    @PostMapping
    public Result<?> submit(
            @RequestBody Feedback feedback,
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenUtil.extractUsername(token.substring(7));
        feedbackService.submit(username, feedback);
        return Result.success();
    }

    @GetMapping("/my")
    public Result<?> getMyFeedback(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenUtil.extractUsername(token.substring(7));
        
        // 添加日志输出查看图片路径
        Page<Feedback> feedbackPage = feedbackService.getMyFeedback(username, page, size);
        feedbackPage.getRecords().forEach(feedback -> {
            log.info("反馈ID: {}, 图片路径: {}", feedback.getId(), feedback.getImages());
        });
        
        return Result.success(feedbackPage);
    }

    @GetMapping("/{id}")
    public Result<?> getDetail(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        String username = jwtTokenUtil.extractUsername(token.substring(7));
        return Result.success(feedbackService.getDetail(username, id));
    }

    // 添加文件上传接口
    @PostMapping("/upload")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 确保目录存在
            String projectPath = System.getProperty("user.dir");
            File dir = new File(projectPath + "/backend/src/main/resources/uploads/feedback");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            File dest = new File(dir.getAbsolutePath() + File.separator + filename);
            file.transferTo(dest);

            // 返回相对路径
            return Result.success("/uploads/feedback/" + filename);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteFeedback(@PathVariable Long id) {
        try {
            feedbackService.deleteFeedback(id);
            return ResponseEntity.ok(new ApiResponse(true, "留言删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new ApiResponse(false, "删除失败: " + e.getMessage()));
        }
    }
} 